package mgodb

import (
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// cRole 角色管理表名
const cRole = "oper_role"

// Role 角色管理
type Role struct {
	DB *mongo.DB
}

// Init 初始化
func (a *Role) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cRole, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("deleted")
		c.EnsureIndexKey("deleted", "status")
		c.EnsureIndexKey("deleted", "status", "record_id")
		return nil
	})

	var val model.IRole = a
	g.Provide(&inject.Object{Value: val, Name: "IRole"})
}

// QueryPage 查询分页数据
func (a *Role) QueryPage(params schema.RoleQueryParam, pageIndex, pageSize uint) (int64, []*schema.RoleQueryResult, error) {
	query := bson.M{
		"deleted": 0,
	}

	if v := params.Status; v != 0 {
		query["status"] = v
	}

	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}

	var total int64
	var items []*schema.RoleQueryResult
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("sequence", "-_id").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// QuerySelect 查询选择数据
func (a *Role) QuerySelect(params schema.RoleSelectParam) ([]*schema.RoleSelect, error) {
	query := bson.M{
		"deleted": 0,
		"status":  1,
	}

	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}

	var items []*schema.RoleSelect
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		return c.Find(query).Sort("sequence").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询选择数据发生错误")
	}
	return items, nil
}

// QueryByIDs 根据ID列表查询数据
func (a *Role) QueryByIDs(recordIDs []string) ([]*schema.Role, error) {
	query := bson.M{
		"deleted":   0,
		"status":    1,
		"record_id": bson.M{"$in": recordIDs},
	}

	var items []*schema.Role
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		return c.Find(query).All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "根据ID列表查询数据发生错误")
	}
	return items, nil
}

// Get 精确查询数据
func (a *Role) Get(recordID string) (*schema.Role, error) {
	var item schema.Role
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": recordID}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "精确查询数据发生错误")
	}
	return &item, nil
}

// CheckName 检查名称是否存在
func (a *Role) CheckName(name string) (bool, error) {
	var exists bool
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		n, err := c.Find(bson.M{"deleted": 0, "name": name}).Count()
		if err != nil {
			return err
		}
		exists = n > 0
		return nil
	})
	if err != nil {
		return false, errors.Wrapf(err, "检查名称是否存在发生错误")
	}

	return exists, nil
}

// Create 创建数据
func (a *Role) Create(item *schema.Role) error {
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cRole)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建数据发生错误")
	}

	return nil
}

// Update 更新数据
func (a *Role) Update(recordID string, info map[string]interface{}) error {
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Delete 删除数据
func (a *Role) Delete(recordID string) error {
	info := map[string]interface{}{
		"deleted": time.Now().Unix(),
	}
	err := a.DB.C(cRole, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "删除数据发生错误")
	}
	return nil
}
